package com.yuanfeng.activity.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanfeng.activity.dto.ActivityExplainParamDTO;
import com.yuanfeng.activity.dto.GiftDTO;
import com.yuanfeng.activity.entity.ActivitySpinwinEntity;
import com.yuanfeng.activity.mapper.ActivitySpinwinLuckyDrawTimesMapper;
import com.yuanfeng.activity.mapper.ActivitySpinwinMapper;
import com.yuanfeng.activity.mapper.ActivitySpinwinPersonMapper;
import com.yuanfeng.activity.mapper.ActivitySpinwinPrizeMapper;
import com.yuanfeng.activity.service.ActivitySpinwinService;
import com.yuanfeng.activity.utils.LotteryUtils;
import com.yuanfeng.activity.vo.DrawTimesDetailsVO;
import com.yuanfeng.activity.vo.SpinWinDrawDetailVO;
import com.yuanfeng.activity.vo.SpinWinDrawTimesVO;
import com.yuanfeng.activity.vo.SpinwinLuckyDrawVO;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.ParseTokenUtils;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.util.querypage.Query;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 */
@Service
public class ActivitySpinwinServiceImpl extends ServiceImpl<ActivitySpinwinMapper, ActivitySpinwinEntity>
    implements ActivitySpinwinService{

    @Autowired
    private ActivitySpinwinLuckyDrawTimesMapper activitySpinwinLuckyDrawTimesMapper;
    @Autowired
    private ActivitySpinwinPersonMapper activitySpinwinPersonMapper;
    @Autowired
    private ActivitySpinwinPrizeMapper activitySpinwinPrizeMapper;
    @Autowired
    private ActivityRedpacketBaseServiceImpl activityRedpacketBaseService;
    @Override
    public ResponseResult updateSpinwinLimit(Map<String, Object> param) {
        this.baseMapper.updateSpinwinLimit(param);
        return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
    }

    @Override
    public ResponseResult querySpinwinLimit(Map<String, Object> param) {
        ActivitySpinwinEntity entity= this.baseMapper.selectById(param.get("activityId").toString());
        return ResponseResult.success(entity);
    }

    @Override
    public ResponseResult deleteSpinwinActivity(Map<String, Object> param) {
        this.baseMapper.deleteById(param.get("activityId").toString());
        return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
    }

    @Override
    public ResponseResult querySpinwinActivityDetail(Map<String, Object> param) {
        ActivitySpinwinEntity entity=this.baseMapper.selectById(param.get("activityId").toString());
        return ResponseResult.success(entity);
    }

    @Override
    public ResponseResult querySpinwinActivityList(Map<String, Object> param) {
        IPage<ActivitySpinwinEntity> page=this.baseMapper.selectSpinwinActivityList(new Query<ActivitySpinwinEntity>().getPage(param),
                param);
        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult updateSpinwinActivity(Map<String, Object> param) {
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(param.get("token").toString());

        param.put("updateBy",userInfo.getUserRealname());
        param.put("updateDate",new Date());
        if (null == param.get("activityId") || param.get("activityId") =="") {
            this.baseMapper.insertSpinwinActivity(param);
        } else {
            this.baseMapper.updateSpinwinActivity(param);
        }

        return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
    }

    @Override
    @Transactional
    public ResponseResult querySpinWinDrawTimes(ActivityExplainParamDTO param) {
        SpinWinDrawTimesVO result = new SpinWinDrawTimesVO();

        SpinWinDrawDetailVO detail = this.baseMapper.selectDrawDetail(param);

        if (null == detail) {
            return ResponseResult.fail(0,"暂未有可用的活动");
        }
        // 获取用户信息
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(param.getToken());
        param.setUserId(userInfo.getUserId());
        param.setUserName(userInfo.getUserName());

        Integer partakeNum = detail.getPartakeNum();
        Integer totalSweepstakes = detail.getTotalSweepstakesLimit();
        Integer winningTimesPerPerson = detail.getWinningTimesPerPerson();

        if (detail.getPartakeNumIsDisplay().intValue() == 1) {
            result.setPartakeNum(partakeNum);
        }

        if (detail.getPartakeNumIsLimit().intValue() == 2
                && partakeNum.intValue() >= detail.getPartakeNumLimit().intValue()) {
            return ResponseResult.success(0,"活动人数已超上限");
        }

        // 查询抽奖次数
        Integer surplusDrawTimes = 0;
        Integer surplusTimes = 0;
        DrawTimesDetailsVO drawTimesDetails = activitySpinwinLuckyDrawTimesMapper.selectDrawTimes(param);

        if (null != drawTimesDetails) {
            surplusDrawTimes = drawTimesDetails.getSurplusDrawTimes();
            surplusTimes = drawTimesDetails.getNumberOfDailyLottery() - drawTimesDetails.getNumSweepstakesToday();
        } else {
            surplusDrawTimes = totalSweepstakes;
            param.setSurplusDrawTimes(surplusDrawTimes);
            param.setLuckyDrawTimes(totalSweepstakes);
            param.setNumberOfDailyLottery(winningTimesPerPerson);
            surplusTimes = winningTimesPerPerson;

            activitySpinwinLuckyDrawTimesMapper.insertDrawTimes(param);
        }

        result.setSurplusDrawTimes(surplusDrawTimes);
        result.setTurntableBackground(detail.getTurntableBackground());
        result.setSurplusTimes(surplusTimes);
        result.setPartakeNumIsLimit(detail.getPartakeNumIsLimit());

        return ResponseResult.success(result);
    }

    @Override
    public ResponseResult queryActivityExplain(ActivityExplainParamDTO param) {
        String graphicExplanation = this.baseMapper.selectActivityExplain(param);

        return ResponseResult.success( graphicExplanation);
    }

    @Override
    public ResponseResult updateLotteryDraw(ActivityExplainParamDTO param) {
        // 获取用户信息
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(param.getToken());

        param.setUserId(userInfo.getUserId());

        SpinWinDrawDetailVO detail = this.baseMapper.selectDrawDetail(param);

        if (null == detail) {
            return ResponseResult.fail(0,"暂未有可用的活动");
        }

        // 判断是否超出参与人数
        // 参与人数
        Integer partakeNum = detail.getPartakeNum();
        // 参与人数限制
        Integer partakeNumLimit = detail.getPartakeNumLimit();
        // 总抽奖机会是否限制：1-不限，2-限制
        Integer totalSweepstakesIsLimit = detail.getTotalSweepstakesIsLimit();
        // 中奖次数
        Integer winningTimesPerPerson = detail.getWinningTimesPerPerson();
        // 总抽奖机会
        Integer totalSweepstakesLimit = detail.getTotalSweepstakesLimit();
        Integer surplusDrawTimes = 0;
        // 用户今日可抽奖次数
        Integer numberOfDailyLottery = 0;
        Integer winningTimes = 0;
        // 用户今日已抽奖次数
        Integer numSweepstakesToday = 0;
        DrawTimesDetailsVO drawTimesDetails = activitySpinwinLuckyDrawTimesMapper.selectDrawTimes(param);

        if (null == drawTimesDetails) {
            if (detail.getPartakeNumLimit().intValue() == 2 && partakeNum.intValue() >= partakeNumLimit.intValue()) {
                return ResponseResult.fail(0,"活动人数已超上限");
            } else {
                numSweepstakesToday = numSweepstakesToday + 1;
                surplusDrawTimes = totalSweepstakesLimit - 1;
                partakeNum = partakeNum + 1;
            }
        } else {
            // 判断抽奖机会
            surplusDrawTimes = drawTimesDetails.getSurplusDrawTimes();
            // 用户今日已抽奖次数
            numSweepstakesToday = drawTimesDetails.getNumSweepstakesToday() + 1;
            winningTimes = drawTimesDetails.getWinningTimes();
            // 用户今日可抽奖次数
            numberOfDailyLottery = drawTimesDetails.getNumberOfDailyLottery();

            if (totalSweepstakesIsLimit.equals(2) && surplusDrawTimes.equals(0)) {
                return ResponseResult.fail(0,"抽奖次数已达上限");
            }

            if (winningTimesPerPerson.intValue() <= drawTimesDetails.getNumSweepstakesToday().intValue()) {
                return ResponseResult.fail(0,"今日抽奖次数已达上限");
            }
            surplusDrawTimes = surplusDrawTimes - 1;
        }

        /**
         * 获取抽奖奖品
         */
        // 查询可用的礼品
        List<GiftDTO> gifts = this.baseMapper.selectActivityGift(param);

        if (CollectionUtils.isEmpty(gifts)) {
            return ResponseResult.fail(0,"暂无可用礼品");
        }

        Integer orignalIndex = LotteryUtils.lottery(gifts);
        GiftDTO giftDTO = gifts.get(orignalIndex);
        // 中奖id;
        Integer prizeId = giftDTO.getPrizeId();
        String prizeName = giftDTO.getPrizeName();
        SpinwinLuckyDrawVO luckyDraw = new SpinwinLuckyDrawVO();
        param.setPrizeId(giftDTO.getPrizeId());

        // 中奖数量
        Integer drawCount = activitySpinwinPersonMapper.selectPrizeRecordCount(param);

        if (drawCount == 0) {
            partakeNum = partakeNum + 1;
        }

        if (giftDTO.getIsWin().equals(1)) {

            if (giftDTO.getIsWin() == 1) {
                winningTimes = winningTimes + 1;
            }
            // 发放红包
            if (giftDTO.getGiftIsRedpacket().equals(1)) {
                Map<String, String> paraMap = new HashMap<>();
                paraMap.put("redpacketTId", giftDTO.getRedpacketTId().toString());
                paraMap.put("redpacketId", "");
                Integer redpacketId = activityRedpacketBaseService.insertSpinwinRpBase(paraMap, userInfo);
                luckyDraw.setRedpacketId(redpacketId);
            }
        }
        // 更新用户抽奖记录
        luckyDraw.setActivityId(param.getActivityId());
        luckyDraw.setPrizeId(prizeId);
        luckyDraw.setUpdateDate(new Date());
        luckyDraw.setUserId(userInfo.getUserId());
        luckyDraw.setUserAvatar(userInfo.getUserAvatar());
        luckyDraw.setUserName(null == userInfo.getUserName() ? userInfo.getUserNickname() : userInfo.getUserName());
        activitySpinwinPersonMapper.insertLuckyDraw(luckyDraw);

        // 更新奖品数量
        activitySpinwinPrizeMapper.updateGiveOutGiftNum(param);
        // 更新抽奖次数
        luckyDraw.setNumSweepstakesToday(numSweepstakesToday);
        luckyDraw.setSurplusDrawTimes(surplusDrawTimes);
        luckyDraw.setNumberOfDailyLottery(numberOfDailyLottery);
        luckyDraw.setWinningTimes(winningTimes);
        if (null == drawTimesDetails) {
            luckyDraw.setLuckyDrawTimes(totalSweepstakesIsLimit);
            activitySpinwinLuckyDrawTimesMapper.insertDrawTimes2(luckyDraw);
        } else {
            luckyDraw.setLuckyDrawTimes(drawTimesDetails.getLuckyDrawTimes() - 1);
            activitySpinwinLuckyDrawTimesMapper.updateDrawTimes(luckyDraw);
        }
        // 更新参与人数
        luckyDraw.setPartakeNum(partakeNum);
        this.baseMapper.updateActivity(luckyDraw);
        Map resultMap = new HashMap();
        resultMap.put("prizeId",prizeId);
        resultMap.put("prizeName",prizeName);
        return ResponseResult.success(resultMap);
    }
}




